<?php

namespace App\Http\Controllers\Admin\newWork;

use App\Http\Config\ErrorCode;
use App\Library\WeChat;
use App\Models\Admin\Configs;
use App\Models\User\UserBase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Excel;
use Illuminate\Support\Str;

class ListController extends CommonController
{
    private $tableName = "new_work_list";
    private $catTableName = "new_work_cat";
    private $typeTableName = "new_work_type";
    private $memberTableName = "member";
    private $adminUserTableName = "admin_users";
    private $workReplyTableName = "new_work_reply";
    private $settingTableName = "new_work_setting";
    private $replyField = [
        "list_id" => "require", "feedback" => "require", "picture" => 'require',
        "annex" => "require"
    ]; // 填入数据库需要存储的表字段;
    private $replyFieldMsg = [
        "list_id" => "所属工单ID", "user_id" => "回复人ID", "feedback" => "反馈内容", "picture" => '图片列表',
        "annex" => "附件列表"
    ];
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    // 工单列表
	public function getPageList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        $pageNo = isset($params["pageNo"]) ? $params["pageNo"] : 1;
        $pageSize = isset($params["pageSize"]) ? $params["pageSize"] : 10;
        $db = DB::table($this->tableName. " as l")->leftJoin("{$this->memberTableName} as m",'l.user_id','=','m.id')
            ->leftJoin("{$this->adminUserTableName} as u",'u.id','=','l.receive_id')
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','l.cat_id')
            ->select("l.id", "m.name as userName", "m.mobile as userMobile", "c.name as catName", "l.feedback", //"l.title",
                "t.name as typeName", "l.create_time", "l.status", "u.name as adminName", "u.mobile as adminMobile",
                "l.receive_time", "l.update_time")
            ->where("l.mall_id", $request->mallData['id']);
        if(!empty($params["search"])){
            $db->where(function ($query) use ($params) {
                $query->where('l.feedback', 'LIKE', '%' . $params["search"] . '%')
                    ->orwhere('m.name', 'LIKE', '%' . $params["search"] . '%');
            });
        }
        if(!empty($params["status"])){
            $db->where("l.status", $params["status"]);
        }
        if(!empty($params["catId"])){
            $db->where("l.cat_id", $params["catId"]);
        }
        if($this->AU['position'] != "超级管理员"){
            $adminUserModel = new UserBase();
            $user_list = $adminUserModel->getAdminSubuser($this->AU["id"]);
            $db->whereIn('l.receive_id', $user_list);
        }
        $data = array(
            'total' => $db->count(),
            'rows' => $db->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("l.create_time", "desc")->get()
        );
        $data['rows'] = $this->transferFields(json_decode(json_encode($data['rows']),true));
        foreach ($data['rows'] as &$item){
            $item["feedback"] = json_decode($item["feedback"], true);
            foreach ($item["feedback"] as $key => $f){
                if(isset($f["reply"])){
                    if($f["type"] == "UploadPicture"){
                        if(is_array($f["reply"])){
                            foreach ($f["reply"] as &$tt){
                                $tt = $this->processingPictures($tt);
                            }
                        }else{
                            $f["reply"] = $this->processingPictures($f["reply"]);
                        }
                    }
                    $item["formItem{$key}"] = $f["reply"];
                }else{
                    $item["formItem{$key}"] = '';
                }
            }
            unset($item["feedback"]);
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    // 导出工单列表
    public function exportListData(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        if(empty($params["id"])){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "ID不能为空");
        }
        $db = DB::table($this->tableName. " as l")->leftJoin("{$this->memberTableName} as m",'l.user_id','=','m.id')
            ->leftJoin("{$this->adminUserTableName} as u",'u.id','=','l.receive_id')
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','l.cat_id')
            ->select("l.id", "m.name as userName", "m.mobile as userMobile", "c.name as catName", "l.feedback", //"l.title",
                "t.name as typeName", "l.create_time", "l.status", "u.name as adminName", "u.mobile as adminMobile",
                "l.receive_time", "l.update_time")
            ->whereIn("l.id", explode(",", $params["id"]))
            ->where("l.mall_id", $request->mallData['id']);
        if($this->AU['position'] != "超级管理员"){
            $adminUserModel = new UserBase();
            $user_list = $adminUserModel->getAdminSubuser($this->AU["id"]);
            $db->whereIn('l.receive_id', $user_list);
        }
        $data = $db->orderBy("l.create_time", "desc")->get();
        $data = $this->transferFields(json_decode(json_encode($data),true));
        $arr[] = ['ID', '提交人', '联系方式', '所属区域', '反馈详情', '问题类别', '提交时间', '状态', "接单人员", "联系方式", "接受时间", "反馈时间"];
        foreach ($data as $k => $v) {
            $arr[] = [
                $v['id'], $v['userName'], $v['userMobile'], $v['catName'], $v['feedback'], $v['typeName'], $v['createTime'],
                ($v['status'] == "1" ? "待签收" : ($v['status'] == "2" ? "处理中" : "已解决")),
                $v['adminName'], $v['adminMobile'], $v['receiveTime'], $v['updateTime'],
            ];
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if ($con->env == 'CLOUD') {
            $temp_file = tempnam(sys_get_temp_dir(), time() . ".xlsx");  //临时文件
            $a = Excel::create('工单列表-'.date("H:i:s"), function ($excel) use ($arr) {
                $excel->sheet('工单列表', function ($sheet) use ($arr) {
                    $sheet->rows($arr);
                });
            })->string('xlsx');
            file_put_contents($temp_file, $a);
            $data['code'] = 3;
            $data['name'] = '工单列表-'.date("H:i:s").'.xlsx';
            $data['data'] = $temp_file;
            return $data;
        } else {
            Excel::create('工单列表-'.date("H:i:s"), function ($excel) use ($arr) {
                $excel->sheet('工单列表', function ($sheet) use ($arr) {
                    $sheet->rows($arr);
                });
            })->export('xlsx');
        }
    }

    // 导出工单详细信息
    public function exportInfoData(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $db = DB::table($this->tableName)->select("id", "feedback", "create_time", "cat_id")
            ->where("mall_id", $request->mallData['id']);
        if($this->AU['position'] != "超级管理员"){
            $adminUserModel = new UserBase();
            $user_list = $adminUserModel->getAdminSubuser($this->AU["id"]);
            $db->whereIn('receive_id', $user_list);
        }
        $data = $db->orderBy("create_time", "desc")->get();
        $data = $this->transferFields(json_decode(json_encode($data),true));
        $list = array_column($data, "id", "catId");
        array_walk($data, function (&$var){
            $var["feedback"] = (array)@json_decode($var["feedback"], true);
        });
        unset($var);
        $arr = $statics = [];
        foreach ($list as $catId => $id){
            $i = 1;
            $arr[$catId]["statics"][0] = ["日期"];
            $arr[$catId][0] = ['ID', '提交时间'];
            $j = count($arr[$catId][0]);
            foreach ($data as $k => $item){
                if($item["catId"] == $catId){
                    $arr[$catId][$i] = [$item['id'], $item['createTime']];
                    array_walk($item["feedback"], function ($var) use(&$arr, $catId, $i, $j){
                        if(!in_array($var["type"], ["UploadPicture", "UploadVoice", "UploadFile"])) {
                            $var["name"] = trim($var["name"]);
                            if(!$j = array_search($var["name"], $arr[$catId][0])) {
                                $arr[$catId][0][] = $var["name"];
                                $j = count($arr[$catId][0]) - 1;
                            }
                            if (isset($var["display"]) && !$var["display"]) {
                                $var["reply"] = '';
                            }
                            $arr[$catId][$i][$j] = $var["reply"] ?? "";
                        }
                        if ($var["type"] == "Radio" && (!isset($var["statistics"]) || $var["statistics"] == '1')) {
                            if ($i < 2) {
                                foreach ($var["options"] as $o) {
                                    $arr[$catId]["statics"][0] = array_merge($arr[$catId]["statics"][0], [$var["name"] . " - {$o["value"]}"]);
                                }
                            }
                            $date = date("Y-m-d", strtotime($arr[$catId][$i][1]));
                            $index = array_search($var["name"] . " - " . ($var["reply"] ?? ""), $arr[$catId]["statics"][0]);
                            $arr[$catId]["statics"][$date][0] = $date;
                            if($index)
                                $arr[$catId]["statics"][$date][$index] = empty($arr[$catId]["statics"][$date][$index]) ? 1 : $arr[$catId]["statics"][$date][$index] + 1;
                        }
                    });
                    $i++;
                    unset($data[$k]);
                }
            }
            foreach (array_keys($arr[$catId]["statics"][0]) as $index){
                array_walk($arr[$catId]["statics"], function (&$value, $key) use($index){
                    if(!is_numeric($key)){
                        $value[$index] = $value[$index] ?? 0;
                        ksort($value);
                    }
                });
            }
            $statics[] = $arr[$catId]["statics"];
            unset($arr[$catId]["statics"]);
            for($i = 1;$i < count($arr[$catId]);$i++){
                for($j = 0;$j < count($arr[$catId][0]);$j++){
                    if(!isset($arr[$catId][$i][$j])){
                        $arr[$catId][$i][$j] = '';
                    }
                }
                ksort($arr[$catId][$i]);
            }
        }
        $arr = array_merge($arr, ["static" => $statics]);
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if ($con->env == 'CLOUD') {
            $temp_file = tempnam(sys_get_temp_dir(), time() . ".xlsx");  //临时文件
            $a = Excel::create('数据列表', function ($excel) use ($arr) {
                foreach ($arr as $k => $item){
                    if(is_numeric($k)) {
                        $excel->sheet('数据列表', function ($sheet) use ($item) {
                            for( $i = 0; $i < count($item[0]); $i++){
                                if(65 + $i < 91){
                                    $mark = chr(65 + $i);
                                }else{
                                    $temp = floor($i / 26);
                                    $mark = chr(65 + $temp - 1) . chr(65 + $i - (26 * $temp));
                                }
                                $sheet->setWidth($mark, 25);//设置列宽
                            }
                            $sheet->rows($item);
                        });
                    }else{
                        foreach ($item as $t){
                            $excel->sheet('数据统计', function ($sheet) use ($t) {
                                for( $i = 0; $i < count($t[0]); $i++){
                                    if(65 + $i < 91){
                                        $mark = chr(65 + $i);
                                    }else{
                                        $temp = floor($i / 26);
                                        $mark = chr(65 + $temp - 1) . chr(65 + $i - (26 * $temp));
                                    }
                                    $sheet->setWidth($mark, 25); //设置列宽
                                }
                                $sheet->rows($t);
                            });
                        }
                    }
                }
            })->string('xlsx');
            file_put_contents($temp_file, $a);
            $data['code'] = 3;
            $data['name'] = '数据列表'.'.xlsx';
            $data['data'] = $temp_file;
            return $data;
        } else {
            Excel::create('数据列表', function ($excel) use ($arr) {
                foreach ($arr as $k => $item){
                    if(is_numeric($k)) {
                        $excel->sheet('数据列表', function ($sheet) use ($item) {
                            for( $i = 0; $i < count($item[0]); $i++){
                                if(65 + $i < 91){
                                    $mark = chr(65 + $i);
                                }else{
                                    $temp = floor($i / 26);
                                    $mark = chr(65 + $temp - 1) . chr(65 + $i - (26 * $temp));
                                }
                                $sheet->setWidth($mark, 25);//设置列宽
                            }
                            $sheet->rows($item);
                        });
                    }else{
                        foreach ($item as $t){
                            $excel->sheet('数据统计', function ($sheet) use ($t) {
                                for( $i = 0; $i < count($t[0]); $i++){
                                    if(65 + $i < 91){
                                        $mark = chr(65 + $i);
                                    }else{
                                        $temp = floor($i / 26);
                                        $mark = chr(65 + $temp - 1) . chr(65 + $i - (26 * $temp));
                                    }
                                    $sheet->setWidth($mark, 25); //设置列宽
                                }
                                $sheet->rows($t);
                            });
                        }
                    }
                }
            })->export('xlsx');
        }
    }

    public function getInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "ID不能为空");
        }
        $data = DB::table($this->tableName. " as l")
            ->leftJoin("{$this->memberTableName} as m",'l.user_id','=','m.id')
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','l.cat_id')
            ->select("l.id", "m.name as userName", "m.mobile as userMobile", "t.name as typeName", "c.name as catName", "l.feedback", //"l.title",
                "l.create_time", "l.status")->where("l.id", $request->id)->first();
        $data = $this->transferFields(json_decode(json_encode($data),true));
        $data["feedback"] = json_decode($data["feedback"], true);
        foreach ($data["feedback"] as $key => &$f){
            if($f["type"] == "UploadPicture" && !empty($f["reply"])){
                $reply = $f["reply"];
                $f["reply"] = [];
                if(is_array($reply)){
                    foreach ($reply as $tt){
                        $f["reply"][] = ["id" => $tt, "url" => $this->processingPictures($tt)];
                    }
                }else{
                    $f["reply"] = ["id" => $reply, "url" => $this->processingPictures($reply)];
                }
            }
        }
        $replyData = DB::table($this->workReplyTableName)
            ->select("feedback", "picture", "annex", "create_time", "user_id", "submit_id")
            ->orderBy("create_time", "desc")
            ->where("list_id", $request->id)->get();
        $replyData = $this->transferFields(json_decode(json_encode($replyData),true));
        foreach ($replyData as &$item){
            $item["annex"] = @json_decode($item["annex"]);
            $picture = !empty($item["picture"]) ? explode(",", $item["picture"]) : [];
            $item["picture"] = [];
            foreach ($picture as $p){
                $item["picture"][] = ["id" => $p, "url" => $this->processingPictures($p)];
            }
            if(!empty($item["userId"])){
                if(!isset($temp["admin"][$item["userId"]])){
                    $tmp = DB::table($this->adminUserTableName)->where("id", $item["userId"])->select("name")->first();
                    $temp["admin"][$item["userId"]] = !empty($tmp->name) ? $tmp->name : "";
                }
                $item["isManage"] = "1";
                $item["name"] = $temp["admin"][$item["userId"]];
            }elseif(!empty($item["submitId"])){
                if(!isset($temp["member"][$item["submitId"]])){
                    $tmp = DB::table($this->memberTableName)->where("id", $item["submitId"])->select("name")->first();
                    $temp["member"][$item["submitId"]] = !empty($tmp->name) ? $tmp->name : "";
                }
                $item["isManage"] = "0";
                $item["name"] = $temp["member"][$item["submitId"]];
            }
        }
        $data["replyData"] = $replyData;
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    public function saveFeedBack(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        $data["create_time"] = date("Y-m-d H:i:s");
        $data["user_id"] = $this->AU["id"];
        foreach ($this->replyField as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if($v === 'require' && !isset($params[$ks])){
                return $this->return_result(ErrorCode::$admin_enum["customized"], "{$this->replyFieldMsg[$k]}不能为空");
            }
            $data[$k] = isset($params[$ks]) ? (is_array($params[$ks]) ? implode(",", $params[$ks]) : trim($params[$ks])) : $v;
        }
        $listData = DB::table($this->tableName . " as l")
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','t.cat_id')
            ->select("l.user_id", "l.status", "l.receive_id", "c.name as catName", "t.name as typeName")
            ->where("l.id", $params["listId"])->first();
        if(empty($listData)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '工单不存在';
            return $this->return_result($this->returnData);
        }
        if($listData->status == '3'){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '工单已解决了';
            return $this->return_result($this->returnData);
        }
        $res = DB::table($this->workReplyTableName)->insert($data);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '提交失败';
            return $this->return_result($this->returnData);
        }
        $updateData = ["status" => 2];
        if(!$listData->receive_id){ // 没有接单人，设置当前人
            $updateData["receive_id"] = $this->AU["id"];
        }
        $this->returnData['msg'] = '提交成功';
        $setting = DB::table($this->settingTableName)->select("wx_reply_template", "sms_reply_template")->where("mall_id", $request->mallData['id'])->first();
        $memberData = DB::table($this->memberTableName)->where("id", $listData->user_id)->select("mobile", "openid")->first();
        if(!empty($memberData->mobile) && $setting->sms_reply_template){
            $this->sendSms($memberData->mobile, $setting->sms_reply_template, [date("Y-m-d H:i:s")]); // 发送短信
        }
        if(!empty($setting->wx_reply_template)){
            $res = WeChat::sendTemplateMsg($memberData->openid, $setting->wx_reply_template, [
                "number1" => ["value" => $params["listId"]], "phrase2" => ["value" => "审核中"], "phrase3" => ["value" => "审核中"]
            ], $msg);
            if(!$res){
                $this->returnData['msg'] .= "，{$msg}";
            }
        }
        DB::table($this->tableName)->where("id", $params["listId"])->update($updateData);
        return $this->return_result($this->returnData);
    }

    public function workOrderFinish(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        if(empty($params["id"])){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "ID不能为空");
        }
        if(DB::table($this->tableName)->where("id", $params["id"])->update(["status" => '3'])){
            $this->returnData['msg'] = '结单成功';
        }else{
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '结单失败';
        }
        return $this->return_result($this->returnData);
    }

    public function delWorkOrder(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        if(empty($params["id"])){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "ID不能为空");
        }
        if(DB::table($this->tableName)->where("id", $request["id"])->delete()){
            $this->returnData['msg'] = '删除成功';
        }else{
            $this->returnData['status'] = 1;
            $this->returnData['msg'] = '删除失败';
        }
        return $this->return_result($this->returnData);
    }
}